package org.dromara.crawler.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.web.core.BaseController;
import org.dromara.crawler.domain.CrawlerTask;
import org.dromara.crawler.mongo.mongodomain.CrawlerLogs;
import org.dromara.crawler.mongo.mongoservice.CrawlerLogsService;
import org.dromara.crawler.service.CrawlerTaskService;
import org.springframework.web.bind.annotation.*;

/**
 * 抓取任务接口
 *
 * @author ddh
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/crawlerTask")
public class CrawlerTaskController extends BaseController {

    private final CrawlerTaskService crawlerTaskService;

    private final CrawlerLogsService crawlerLogsService;

    /**
     * 创建爬虫任务
     */
    @PostMapping("/add")
    public R<Boolean> add(@RequestBody CrawlerTask crawlerTask) {
        crawlerTask.setStatus("0");
        return R.ok(crawlerTaskService.save(crawlerTask));
    }


    /**
     * 删除爬虫任务
     */
    @DeleteMapping("/deleteTask/{taskId}")
    public R<Boolean> deleteTask(@PathVariable Long taskId) {
        return R.ok(crawlerTaskService.deleteTask(taskId));
    }

    /**
     * 分页查询
     */
    @GetMapping("/queryByPage")
    public R<IPage<CrawlerTask>> queryByPage(CrawlerTask crawlerTask, PageQuery pageQuery) {
        return R.ok(crawlerTaskService.queryByPage(crawlerTask, pageQuery));
    }

    /**
     * 根据ID查询
     */
    @GetMapping("/getById")
    public R<CrawlerTask> getById(Long crawlerTaskId) {
        return R.ok(crawlerTaskService.getById(crawlerTaskId));
    }

    /**
     * 根据任务Id查询抓取日志
     */
    @GetMapping("/getLogByTaskId")
    public R<CrawlerLogs> getLogByTaskId(String taskId) {
        return R.ok(crawlerLogsService.getLogByTaskId(taskId));
    }

    /***
     * 启动任务
     * @param taskId
     * @return
     */
    @PutMapping("/taskRun")
    public R<Boolean> taskRun(Long taskId) {
        return R.ok(crawlerTaskService.runTask(taskId));
    }

    /**
     * 停止任务
     * @param taskId
     * @return
     */
    @PutMapping("/taskStop")
    public R<Boolean> taskStop(Long taskId) {
        return R.ok(crawlerTaskService.stopTask(taskId));
    }

}
